#include "ftshowtext.h"

#include "ftcontrols.h"
#include "ftpushbutton.h"
#include "ftlabel.h"
#include "ftvboxlayout.h"

#define FTST_HOW_OVERLAP 20

FTShowText::FTShowText(const QString& t, const QString& h, QWidget *) :
    RotatingDialog()
{
    buildWidgets(t);
    buildText(h);
    scroll_pos  = 0;
    setSizePolicy( QSizePolicy::Ignored, QSizePolicy::Ignored );
}

void FTShowText::buildWidgets(const QString & t)
{
    titleLabel = new FTLabel( t );
    titleLabel->setTitle(true);
    titleLabel->setAlignment( Qt::AlignHCenter );
    closeButton = new FTPushButton( tr("Close") );
    connect( closeButton, SIGNAL(clicked()),
            this, SLOT(reject()) );
}

void FTShowText::buildText(const QString & h)
{
    QPalette pal;
    QFont helpFont = FTControls::font( FTControls::FontNormal );
    QColor background_color = pal.color( QPalette::Window );
    QColor text_color = pal.color( QPalette::Text );

    QString css = QString("<style type='text/css'>html ") +
            QString("{background-color: %1; ").arg(background_color.name()) +
            QString("color: %1; ").arg( text_color.name() ) +
            QString("font-size: %1px; ").arg( (int)((double)helpFont.pixelSize()) ) +
            QString("font-family: %1; ").arg( helpFont.family() ) +
#ifdef Q_OS_ANDROID
            QString("font-style: italic; ") +
#endif
            QString("width: 100%; ") +
            QString("text-align: left; ") +
            QString("} h2 { text-align: left; } </style>");
    page.mainFrame()->setHtml( css+h );

    connect( page.mainFrame(), SIGNAL(contentsSizeChanged(QSize)),
             this, SLOT(contentsChanged(QSize)) );
}

void FTShowText::contentsChanged(QSize)
{
    update();
}

void FTShowText::paintEvent(QPaintEvent * )
{
    QPainter painter(this);
    painter.translate( 0, titleLabel->height() );
    page.setViewportSize( QSize( width(), height() - closeButton->height() - titleLabel->height() ) );
    page.mainFrame()->setScrollBarValue( Qt::Vertical, scroll_pos );
    page.mainFrame()->render(&painter);
}


void FTShowText::mousePressEvent(QMouseEvent * me )
{
    setMouseTracking(true);
    mouse_start = me->globalY();
}

void FTShowText::mouseReleaseEvent(QMouseEvent *)
{
    setMouseTracking(false);
}

void FTShowText::mouseMoveEvent(QMouseEvent * me)
{
    scroll_pos += mouse_start - me->globalY();
    mouse_start = me->globalY();
    update();
}

QLayout* FTShowText::createVertical()
{
    FTVBoxLayout* grid = new FTVBoxLayout();
    grid->addWidget( titleLabel );
    grid->addStretch(2);
    grid->addWidget( closeButton );
    return grid;
}
